"""
认证API路由
"""
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity, get_jwt
from sqlalchemy.exc import IntegrityError
from datetime import datetime

from lemon_backend.models import User, db_session
from lemon_backend.utils.auth import generate_tokens, error_response

# 创建认证蓝图
auth_bp = Blueprint('auth', __name__, url_prefix='/api/auth')

@auth_bp.route('/register', methods=['POST'])
def register():
    """
    用户注册端点

    请求体:
    {
        "username": "用户名",
        "email": "邮箱",
        "password": "密码"
    }

    返回:
    {
        "message": "注册成功",
        "user": {
            "id": 用户ID,
            "username": "用户名",
            "email": "邮箱"
        }
    }
    """
    data = request.get_json()

    # 验证请求数据
    if not data:
        return error_response("无效的请求数据")

    username = data.get('username')
    email = data.get('email')
    password = data.get('password')

    if not username or not email or not password:
        return error_response("用户名、邮箱和密码不能为空")

    # 检查用户名和邮箱是否已存在
    if User.query.filter_by(username=username).first():
        return error_response("用户名已存在")

    if User.query.filter_by(email=email).first():
        return error_response("邮箱已存在")

    # 创建新用户
    try:
        user = User(username=username, email=email, password=password)
        db_session.add(user)
        db_session.commit()

        return jsonify({
            "message": "注册成功",
            "user": user.to_dict()
        }), 201

    except IntegrityError:
        db_session.rollback()
        return error_response("注册失败，请稍后重试")

    except Exception as e:
        db_session.rollback()
        return error_response(f"注册失败: {str(e)}")

@auth_bp.route('/login', methods=['POST'])
def login():
    """
    用户登录端点

    请求体:
    {
        "username": "用户名",
        "password": "密码"
    }

    返回:
    {
        "message": "登录成功",
        "user": {
            "id": 用户ID,
            "username": "用户名",
            "email": "邮箱"
        },
        "access_token": "访问令牌",
        "refresh_token": "刷新令牌"
    }
    """
    data = request.get_json()

    # 验证请求数据
    if not data:
        return error_response("无效的请求数据")

    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        return error_response("用户名和密码不能为空")

    # 查找用户
    user = User.query.filter_by(username=username).first()

    if not user or not user.check_password(password):
        return error_response("用户名或密码错误", 401)

    if not user.is_active:
        return error_response("账户已被禁用", 403)

    # 更新最后登录时间
    user.last_login = datetime.utcnow()
    db_session.commit()

    # 生成令牌
    tokens = generate_tokens(user.id)

    return jsonify({
        "message": "登录成功",
        "user": user.to_dict(),
        **tokens
    })

@auth_bp.route('/refresh', methods=['POST'])
@jwt_required(refresh=True)
def refresh():
    """
    刷新访问令牌端点

    请求头:
    Authorization: Bearer <refresh_token>

    返回:
    {
        "access_token": "新的访问令牌"
    }
    """
    # 获取当前用户ID
    current_user_id = get_jwt_identity()

    # 查找用户
    user = User.query.get(current_user_id)

    if not user or not user.is_active:
        return error_response("用户不存在或已被禁用", 403)

    # 更新最后登录时间
    user.last_login = datetime.utcnow()
    db_session.commit()

    # 生成新的访问令牌
    access_token = generate_tokens(user.id)['access_token']

    return jsonify({
        "access_token": access_token
    })

@auth_bp.route('/me', methods=['GET'])
@jwt_required()
def me():
    """
    获取当前用户信息端点

    请求头:
    Authorization: Bearer <access_token>

    返回:
    {
        "user": {
            "id": 用户ID,
            "username": "用户名",
            "email": "邮箱"
        }
    }
    """
    # 获取当前用户ID
    current_user_id = get_jwt_identity()

    # 查找用户
    user = User.query.get(current_user_id)

    if not user:
        return error_response("用户不存在", 404)

    if not user.is_active:
        return error_response("账户已被禁用", 403)

    return jsonify({
        "user": user.to_dict()
    })
